<?php

namespace app\admin\command;

use app\admin\controller\task\Task;
use think\console\Command;
use think\Config;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Log;


class Limit extends Command
{

    protected $start_am;
    protected $start_pm;
    protected $stop_am;
    protected $stop_pm;


    protected function configure()
    {
        $this->setName('limit')
            ->setDescription('Dial outbound calls automatically');
    }


    protected function execute(Input $input, Output $output)
    {
//        ob_start();
        $this->stop_am = '12:00:00';
        $this->start_pm = '13:30:00';

        $loop = 0;
        $loop++;
        $loop = ($loop >= PHP_INT_MAX) ? 1 : $loop;
        echo "\r\n------ LimitTimeTask Execute Loop: {$loop} ------\r\n";

        //暂停任务
        $data = Db::name('task')
            ->where('state',1)
            ->where('start','<>','null')
            ->where('stop','<>','null')
            ->select();

        $time = date('H:i:s');

        foreach ($data as $value){

	        if($value['start']=='00:00:00'){
                $value['start'] = '09:00:00';
            }

            if($value['stop']=='00:00:00'){
                $value['stop'] = '19:00:00';
            }

            if(($time <$value['start'] || $time > $value['stop']) || ($time > $this->stop_am && $time < $this->start_pm)){
                Db::name('task')
                    ->where('id',$value['id'])
                    ->update(['state'=>0]);
                Log::info('更新任务task_id:'.$value['id'].'状态为暂停');
            }

        }


        //开启任务
        $startData = Db::query("select * from fa_task where start != 'null' and stop != 'null' and manual_status =0 and ((progress ='0%' and state = '2') or state = '0') ");

        foreach ($startData as $value) {

	        if($value['start']=='00:00:00'){
                $value['start'] = '09:00:00';
            }

            if($value['stop']=='00:00:00'){
                $value['stop'] = '19:00:00';

            }



            if (($time > $value['start'] && $time < $this->stop_am) || ($time > $this->start_pm && $time < $value['stop'])) {
                Db::name('task')
                    ->where('id',$value['id'])
                    ->update(['state'=>1]);
                Log::info('【limit】更新任务task_id:'.$value['id'].'状态为开始');
            }
        }


    }


}
